package hu.monitor.remoting.server;

import hu.monitor.remoting.InvocationContext;
import hu.monitor.remoting.Invoker;
import hu.monitor.remoting.InvokerInterceptor;

import javax.annotation.PostConstruct;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class EjbInvokerInterceptor implements InvokerInterceptor {
	private Context context;

	@PostConstruct
	public void start() throws NamingException {
		this.context = new InitialContext();
	}

	@Override
	public Object intercept(final InvocationContext invocationContext) throws Throwable {
		final String jndiName = this.makeJndiName(invocationContext);
		final Object bean = this.context.lookup(jndiName);
		final Invoker invoker = new Invoker(invocationContext, bean);
		return invoker.invoke();
	}

	private String makeJndiName(final InvocationContext invocationContext) {
		final Class<?> remoteInterface = invocationContext.getRemoteInterface();
		final String beanName = remoteInterface.getSimpleName();
		final String interfaceName = remoteInterface.getName();
		return String.format("java:global/server/%sBean!%s", beanName, interfaceName);
	}

}
